﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OSGeo.MapGuide;
using NegevGas;
using System.Web.Services;
using System.Xml;
using System.Text;
using System.IO;

using System.Net;
using System.Diagnostics;
using System.Reflection;
using System.Configuration;
using System.Collections.Specialized;

namespace NegevGas.Extensions.findlocation
{
    public partial class findlocationM :utilityfunctions 
    {
        public findlocationfunctions jsonlf = new findlocationfunctions();
       public  String mgSessionId;// = GetRequestParameters()["SESSION"];
      public   String mgMap;// = GetRequestParameters()["MAPNAME"];
        bool showPreviousResults = false;
       public  MgSiteConnection siteConnection = null;
       public  String dblKanam;
      public  decimal LatInput = 0;
      public  decimal LonInput = 0;
        
       findlocationfunctions lf = new findlocationfunctions();
       public bool success = false;
      
       //GeocodeAddress addr = null;

       
        protected void Page_Load(object sender, EventArgs e)
        {             
                try
                {
                   // if (!System.Diagnostics.Debugger.IsAttached)
                     //   Debugger.Launch();
                    //if (IsDebugAssembly(this.GetType().Assembly))
                    //    System.Diagnostics.Debugger.Launch();
                        mgSessionId = GetRequestParameters()["SESSION"];
                        mgMap = GetRequestParameters()["MAP"];
                        dblKanam = kanam.Value;
                        //String address = "";

                        //String LatStream = Request["LatStream"].ToString();
                        //String LonStream = Request["LonStream"].ToString();
                        char[] chSplit = { ',' };
                        //string[] LonArray = LatStream.Split(chSplit);
                        //string[] LatArray = LatStream.Split(chSplit); 


                        // Initialize the web-extensions and connect to the Site using
                        // the session identifier stored

                        this.InitializeWebTier();
                        if (!Page.IsPostBack)
                        {
                            ClearSessions();
                        }
                        
                    
                   
                        

                }
                catch (MgException mge)
                {
                   // Response.Write(mge.GetExceptionMessage());
                    //Response.Write(mge.GetDetails());
                }


        }
        // Create a temporary Layer to display geocode results.

   public static bool IsDebugAssembly(Assembly assm)
        {

            foreach (object attr in assm.GetCustomAttributes(false))
            {

                if (attr is DebuggableAttribute)
                {

                    return ((DebuggableAttribute)attr).IsJITTrackingEnabled;

                }

            }

            return false;

        }



        public static void EmitLocationResults(MgFeatureService featureService, MgResourceIdentifier locationMarkerDataResId, String mgSessionId, HttpResponse response)
        {
            //targets.InnerHtml+="<table class=\"RegText\" border=\"0\" cellspacing=\"0\" width=\"100%\">";
            //targets.InnerHtml+="<tr><td class=\"SubTitle\">תוצאות</td></tr>";

            MgAgfReaderWriter geometryReaderWriter = new MgAgfReaderWriter();
            MgFeatureReader featureReader = featureService.SelectFeatures(locationMarkerDataResId, "LocationMarker", null);

            while (featureReader.ReadNext())
            {
                String address = featureReader.GetString("Address");
                MgByteReader byteReader = featureReader.GetGeometry("Location");

                MgPoint point = geometryReaderWriter.Read(byteReader) as MgPoint;
                double x = point.GetCoordinate().GetX();
                double y = point.GetCoordinate().GetY();

                //    targets.InnerHtml+="<tr><td>";
                //   targets.InnerHtml+="<img src=\"../images/pushpinblue.jpg\">";
                //    targets.InnerHtml += "<a href=\"gotopoint.aspx?X=" + x + "&Y=" + y + "&Scale=10000\" target=\"scriptFrame\">X: " + x + ", Y: " + y + "</a></td></tr>";
            }
            featureReader.Close();

            //targets.InnerHtml+="</table>";
            // targets.InnerHtml+="<form action=\"clearlocationresults.aspx\" method=\"get\" target=\"scriptFrame\">";
            //targets.InnerHtml+="<input type=\"hidden\" name=\"SESSION\" value=\"" + mgSessionId + "\">";
            // targets.InnerHtml+="<input type=\"button\" class=\"Ctrl\" value=\"נקה תוצאות \" onClick=\"javascript:submit()\">";
            //targets.InnerHtml+="</form>";
            // targets.InnerHtml+="<hr>";
        }

        public static bool DataSourceExists(MgResourceService resourceSrvc, MgResourceIdentifier dataSourceId)
        {
            try
            {
                string MGServerVersion = ConfigurationManager.AppSettings["MGServerVersion"];
                if (MGServerVersion == "2009")
                {
                    MgByteReader cnt = resourceSrvc.GetResourceContent(dataSourceId);
                    cnt = null;
                    return true;
                }
                return resourceSrvc.ResourceExists(dataSourceId);
            }
            catch (MgResourceNotFoundException)
            {
                return false;
            }
        }


        void CreateLocationMarkerFeatureSource(MgFeatureService featureService, MgResourceIdentifier locationMarkerDataResId)
        {
            String ll84Wkt = "GEOGCS[\"LL84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.25722293287],TOWGS84[0,0,0,0,0,0,0]],PRIMEM[\"Greenwich\",0],UNIT[\"Degrees\",1]]";

            MgClassDefinition locationClass = new MgClassDefinition();
            locationClass.SetName("LocationMarker");
            MgPropertyDefinitionCollection properties = locationClass.GetProperties();

            MgDataPropertyDefinition idProperty = new MgDataPropertyDefinition("ID");
            idProperty.SetDataType(MgPropertyType.Int32);
            idProperty.SetReadOnly(true);
            idProperty.SetNullable(false);
            idProperty.SetAutoGeneration(true);
            properties.Add(idProperty);

            MgDataPropertyDefinition addressProperty = new MgDataPropertyDefinition("Address");
            addressProperty.SetDataType(MgPropertyType.String);
            addressProperty.SetLength(512);
            properties.Add(addressProperty);

            MgGeometricPropertyDefinition locationProperty = new MgGeometricPropertyDefinition("Location");
            locationProperty.SetGeometryTypes(MgGeometryType.Point);
            locationProperty.SetHasElevation(false);
            locationProperty.SetHasMeasure(false);
            locationProperty.SetReadOnly(false);
            locationProperty.SetSpatialContextAssociation("LL84");
            properties.Add(locationProperty);

            MgPropertyDefinitionCollection idProperties = locationClass.GetIdentityProperties();
            idProperties.Add(idProperty);

            locationClass.SetDefaultGeometryPropertyName("Location");

            MgFeatureSchema locationSchema = new MgFeatureSchema();
            locationSchema.SetName("LocationMarkerSchema");
            locationSchema.GetClasses().Add(locationClass);

            MgCreateSdfParams sdfParams = new MgCreateSdfParams("LL84", ll84Wkt, locationSchema);

            featureService.CreateFeatureSource(locationMarkerDataResId, sdfParams);
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Xcoord.Value) || string.IsNullOrEmpty(Ycoord.Value) || string.IsNullOrEmpty(kanam.Value))
            {
           //   Response.Write("<script type='text/javascript'>try{ zoom();}catch(e){}</script>");
                ClientScript.RegisterStartupScript(GetType(), "zoomme", "<script>try{ zoomzfd();}catch(e){}</script>");
              return;
            }

            /*
            

     String mgSessionId = GetRequestParameters()["SESSION"];
     String mgMap = GetRequestParameters()["map"];
     //GeocodeAddress addr = null;
     bool success = false;
     decimal LatInput=0;
     decimal LonInput=0;*/

          
                // Initialize the web-extensions and connect to the Site using
                // the session identifier passed in the query string.
             
            try
            {
               
                InitializeWebTier();
                //MgUserInformation userInfo = new MgUserInformation(mgSessionId);
         
              //  mgSessionId = site.CreateSession();
                MgUserInformation userInfo = new MgUserInformation(mgSessionId);
                MgSiteConnection siteConnection = new MgSiteConnection();
               siteConnection.Open(userInfo);
                decimal LatInput = System.Convert.ToDecimal(Xcoord.Value);
                decimal LonInput = System.Convert.ToDecimal(Ycoord.Value);
                /* LatInput = System.Convert.ToDecimal(GetRequestParameters()["LatInput"]);
                 LonInput = System.Convert.ToDecimal(GetRequestParameters()["LonInput"]);*/

                // Make the request to geocoder.us passing the address.
                //addr = requestGeocodeAddress(address);

                if (LatInput != 0 && LonInput != 0)
                {
                      //Request the specified address to the geocode service using REST, the
        // GET interface
        //

                    if (targetsnew.InnerHtml == "")
                    {
                        targetsnewTitle.InnerHtml = "מיקום נוכחי :";
                        targetsoldTitle.InnerHtml = "";
                        targetsnew.InnerHtml = "<table>";
                        targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">";
                        targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\">  מיקום נמצא </a></td></tr>";
                        targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>";
                        targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>";
                        targetsnew.InnerHtml += "</table>";
                    }
                    else
                    {
                        targetsoldTitle.InnerHtml = "מיקום קודם :";
                        targetsold.InnerHtml += targetsnew.InnerHtml;
                        targetsnew.InnerHtml = "<table>";
                        targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">";
                        targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\">  מיקום נמצא </a></td></tr>";
                        targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>";
                        targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>";
                        targetsnew.InnerHtml += "</table>";
                        
                      
                    }
                    // The geocode successfully returned a location.

                    //if (IsDebugAssembly(this.GetType().Assembly))
                    //    System.Diagnostics.Debugger.Launch();
                    MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
                    MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

                    MgMap map = new MgMap();
                  map.Open(resourceService, mgMap);
                 //   map.Open(mgMap);
                    // Check the map for the AddressMarker layer. If it does not
                    // exist then create a feature source to store address results
                    // and a layer to display them.
                    MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Session:" + mgSessionId + "//LocationMarker.FeatureSource");
                  //  Session:7f4231a2-0d7e-11e2-8000-000c294ca3a6_en_7F0000010AFC0AFB0AFA//a2f5e4fb-0c3c-4ee7-bb5d-c8f4a226a68b.FeatureSource
                   // MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Library://rany1/Data/findLocation/temp/LocationMarker.FeatureSource");
                  //  string layerDef = "Session:" + mgSessionId + "//LocationMarker.FeatureSource";
                    //string dataSource = "Library://rany1/Data/LocationMarker.FeatureSource";

                    /*string layerDef  = "Library://rany1/Layers/LocationMarker.LayerDefinition";

                    MgLayerCollection colLays = map.GetLayers();

                    MgLayer layer = FindLayer(colLays, layerDef);*/

                    ////                       MgLayer locationLayer = FindLayerByName(,"LocationMarker") ;//GetLayerByName(map, "LocationMarker");

                    //MgLayerCollection colLays = map.GetLayers();
                    MgLayerCollection colLays = map.GetLayers();
                    MgLayer locationLayer = FindLayerByName(colLays, "LocationMarker");



                    if (locationLayer == null)
                    {
                       // diverr.InnerHtml += " לא נמצאו שכבות LocationMarker ";
                        lf.CreateLocationMarkerFeatureSource(featureService, locationMarkerDataResId, map);
                        locationLayer = lf.CreateLocationMarkerLayer(resourceService, locationMarkerDataResId, mgSessionId);

                        map.GetLayers().Insert(0, locationLayer);
                    }
                    else if (locationLayer.GetVisible())
                    {
                        // If the layer exists and is visible, then display the
                        // previous results.

                        //EmitAddressResults(featureService, locationMarkerDataResId, mgSessionId, Response);
                        EmitLocationResults(featureService, locationMarkerDataResId, mgSessionId, HttpContext.Current.Response);
                    }

                    // Insert the results of the Geo-Code into the temporary
                    // feature source and ensure the address marker layer
                    // is visible.

                    MgAgfReaderWriter geometryReaderWriter = new MgAgfReaderWriter();
                    MgGeometryFactory geometryFactory = new MgGeometryFactory();
                    MgPoint locationPoint = geometryFactory.CreatePoint(geometryFactory.CreateCoordinateXY(Convert.ToDouble(LonInput), Convert.ToDouble(LatInput)));

                    MgPropertyCollection properties = new MgPropertyCollection();
                    properties.Add(new MgStringProperty("Address", ""));
                    properties.Add(new MgGeometryProperty("Location", geometryReaderWriter.Write(locationPoint)));

                    MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
                    commands.Add(new MgInsertFeatures("LocationMarker", properties));

                    featureService.UpdateFeatures(locationMarkerDataResId, commands, false);

                    locationLayer.SetVisible(true);
                    locationLayer.ForceRefresh();

                    map.Save(resourceService);

                    Response.Write("<script type='text/javascript'>try{ parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>");
                    /* success = true;*/
                  
                }
                else
                {
                    // Response.Write("<tr><td>נקודת הציון לא נמצאה: <hr></td></tr>");
                }
            }
            catch (MgException eee)
            {
               // Response.Write("<script type='text/javascript'>try{alert('rany'); parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>");
               // Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>");
             //   Response.Write("<tr><td>" + eee.InnerException.Message + "</td></tr>");
                Response.Write("<tr><td>" + eee.ToString() + "</td></tr>");
                Response.Write("<tr><td>" + eee.GetBaseException() + "</td></tr>");
                Response.Write("<tr><td>" + eee.GetStackTrace()+ "</td></tr>");
                Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>");
          
                  Response.Write("<tr><td class=\"Spacer\"></td></tr>");
                 // Response.Write("<tr><td>" + eee.GetDetails() + "</td></tr>");
            }
        }
        public static MgClassDefinition CreateFeatureClass(string name, string desc)
        {
            MgClassDefinition classDef = new MgClassDefinition();
            classDef.SetName(name);
            classDef.SetDescription(desc);
            classDef.SetDefaultGeometryPropertyName("GEOM");
            return classDef;
        }
        public static void AddFeatureClassProperty(MgClassDefinition classDef, string name, int itype, bool isKey)
        {
            MgDataPropertyDefinition prop = new MgDataPropertyDefinition(name);
            prop.SetDataType(itype);
            if (isKey)
            {
                prop.SetAutoGeneration(true);
                classDef.GetIdentityProperties().Add(prop);
                prop.SetReadOnly(true);
            }
            else
            {
                prop.Nullable = true;
            }
            classDef.GetProperties().Add(prop);
        }
        public static void SetGeometryProp(MgClassDefinition classDef)
        {
            MgGeometricPropertyDefinition geomProp = new MgGeometricPropertyDefinition("GEOM");
            geomProp.SetGeometryTypes(4);
            classDef.GetProperties().Add(geomProp);
        }
        public static MgFeatureSchema CreateSchema(MgClassDefinition classDef, string name, string desc)
        {
            MgFeatureSchema schema = new MgFeatureSchema(name, desc);
            schema.GetClasses().Add(classDef);
            return schema;
        }
        public static string GetMapSrs(MgMap map)
        {
            string srs = map.GetMapSRS();
            if (srs != "")
            {
                return srs;
            }
            return "LOCALCS[\"Non-Earth (Meter)\",LOCAL_DATUM[\"Local Datum\",0],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
        }
        public static void AddPointFeature(string FeatureName, MgPropertyCollection featureProps, MgPoint geom, MgFeatureService featureSrvc, MgResourceIdentifier dataSourceId)
        {
            MgByteReader geomReader = new MgAgfReaderWriter().Write(geom);
            MgGeometryProperty geometryProp = new MgGeometryProperty("GEOM", geomReader);
            featureProps.Add(geometryProp);
            MgInsertFeatures cmd = new MgInsertFeatures(FeatureName, featureProps);
            MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
            commands.Add(cmd);
            ReleaseReader(featureSrvc.UpdateFeatures(dataSourceId, commands, false));
        }
        public static void ReleaseReader(MgPropertyCollection res)
        {
            if (res != null)
            {
                MgProperty prop = res.GetItem(0);
                if (prop != null)
                {
                    if (prop is MgStringProperty)
                    {
                        throw new Exception(((MgStringProperty)prop).GetValue());
                    }
                    MgFeatureReader reader = ((MgFeatureProperty)prop).GetValue();
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
        public static MgLayer FindLayer(MgLayerCollection layers, string layerDef)
        {
            for (int i = 0; i < layers.GetCount(); i++)
            {
                MgLayer layer1 = (MgLayer)layers.GetItem(i);
                if (layer1.GetLayerDefinition().ToString() == layerDef)
                {
                    return layer1;
                }
            }
            return null;
        }
        public static MgLayer FindLayerByName(MgLayerCollection layers, string layerName)
        {
            for (int i = 0; i < layers.GetCount(); i++)
            {
                if (layers.GetItem(i).GetName().ToLower() == layerName.ToLower())
                {
                    return (layers.GetItem(i) as MgLayer);
                }
            }
            return null;
        }
        private void ClearSessions()
        {
         try
            {
                InitializeWebTier();

                MgUserInformation userInfo = new MgUserInformation(mgSessionId);
                MgSiteConnection siteConnection = new MgSiteConnection();
                siteConnection.Open(userInfo);
                MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
                MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

                MgMap map = new MgMap();
                map.Open(resourceService, mgMap);


                MgLayerCollection layerCol = map.GetLayers();



                string layerName = "LocationMarker";

MgLayer layerToRemove = null;
foreach(MgLayer layer in layerCol)
{
      if(layer.Name == layerName)
      {
            layerToRemove = layer;
            break;
      }
}

if(layerToRemove != null)
{
      layerCol.Remove(layerToRemove);
}




                map.Save(resourceService);
                Xcoord.Value = "";
                Ycoord.Value = "";
                kanam.Value = "10000";
                targetsnewTitle.InnerHtml = "";
                targetsnew.InnerHtml = "";
                targetsold.InnerHtml="";
                targetsoldTitle.InnerHtml = "";

                Response.Write("<script>try{ parent.parent.mapFrame.Refresh();   parent.parent.mapFrame.ZoomToSelection();}catch(e){}</script>");
                /* success = true;*/
            
            }
            catch (Exception exx)
            { 
            
            }

        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            try
            {
                InitializeWebTier();

                MgUserInformation userInfo = new MgUserInformation(mgSessionId);
                MgSiteConnection siteConnection = new MgSiteConnection();
                siteConnection.Open(userInfo);
                MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
                MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

                MgMap map = new MgMap();
                map.Open(resourceService, mgMap);


                MgLayerCollection layerCol = map.GetLayers();



                string layerName = "LocationMarker";

MgLayer layerToRemove = null;
foreach(MgLayer layer in layerCol)
{
      if(layer.Name == layerName)
      {
            layerToRemove = layer;
            break;
      }
}

if(layerToRemove != null)
{
      layerCol.Remove(layerToRemove);
}




                map.Save(resourceService);
                Xcoord.Value = "";
                Ycoord.Value = "";
                kanam.Value = "10000";
                targetsnewTitle.InnerHtml = "";
                targetsnew.InnerHtml = "";
                targetsold.InnerHtml="";
                targetsoldTitle.InnerHtml = "";

                Response.Write("<script>try{ parent.parent.mapFrame.Refresh();   parent.parent.mapFrame.ZoomToSelection();}catch(e){}</script>");
                /* success = true;*/
            
            }
            catch (Exception exx)
            { 
            
            }


        }


       
       
    }
}